/* add user code begin Header */
/**
  **************************************************************************
  * @file     main.c
  * @brief    main program
  **************************************************************************
  *                       Copyright notice & Disclaimer
  *
  * The software Board Support Package (BSP) that is made available to
  * download from Artery official website is the copyrighted work of Artery.
  * Artery authorizes customers to use, copy, and distribute the BSP
  * software and its related documentation for the purpose of design and
  * development in conjunction with Artery microcontrollers. Use of the
  * software is governed by this copyright notice and the following disclaimer.
  *
  * THIS SOFTWARE IS PROVIDED ON "AS IS" BASIS WITHOUT WARRANTIES,
  * GUARANTEES OR REPRESENTATIONS OF ANY KIND. ARTERY EXPRESSLY DISCLAIMS,
  * TO THE FULLEST EXTENT PERMITTED BY LAW, ALL EXPRESS, IMPLIED OR
  * STATUTORY OR OTHER WARRANTIES, GUARANTEES OR REPRESENTATIONS,
  * INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
  *
  **************************************************************************
  */
/* add user code end Header */

/* Includes ------------------------------------------------------------------*/
#include "at32f421_wk_config.h"
#include "wk_adc.h"
#include "wk_tmr.h"
#include "wk_usart.h"
#include "wk_wdt.h"
#include "wk_dma.h"
#include "wk_system.h"

/* private includes ----------------------------------------------------------*/
/* add user code begin private includes */
#include "string.h"
#include "stdio.h"
#include "stdint.h"
#include "string.h"
#include <math.h>
#include <stdlib.h>

#define SIZE 300
/* add user code end private includes */

/* private typedef -----------------------------------------------------------*/
/* add user code begin private typedef */

/* add user code end private typedef */

/* private define ------------------------------------------------------------*/
/* add user code begin private define */

/* add user code end private define */

/* private macro -------------------------------------------------------------*/
/* add user code begin private macro */
volatile uint8_t usart1_tx_dma_status = 0;
volatile uint8_t usart1_rx_dma_status = 0;

volatile uint8_t usart1_rx_buffer[DMA1_CHANNEL3_BUFFER_SIZE];
volatile uint16_t usart1_rx_buffer_size = 0;

volatile uint16_t adc1_ordinary_valuetab[DMA1_CHANNEL1_BUFFER_SIZE];

uint8_t Darllen_amserol_ADC_flag = 0; // 0: no data 1: data ready
uint8_t DIM_flag = 0; // 0: no data 1: data ready
uint8_t Cymhareb_pŵer_celc = 0; //缓存功率

int lastNum = 0; // 记录上一次的输入值
int scenario_num = 4; // 记录当前场景

uint16_t rgb[61][3] = {
        {922, 67, 11},
        {879, 115, 7},
        {837, 160, 4},
        {798, 194, 9},
        {758, 235, 8},
        {719, 273, 8},
        {682, 310, 8},
        {646, 344, 10},
        {619, 353, 28},
        {586, 383, 31},
        {555, 410, 35},
        {534, 411, 56},
        {510, 421, 69},
        {488, 430, 83},
        {466, 437, 97},
        {447, 442, 111},
        {429, 446, 125},
        {412, 448, 140},
        {397, 449, 155},
        {382, 449, 169},
        {369, 448, 184},
        {356, 446, 198},
        {345, 443, 212},
        {334, 440, 226},
        {324, 436, 240},
        {314, 432, 254},
        {306, 427, 267},
        {297, 422, 281},
        {290, 416, 294},
        {283, 411, 306},
        {277, 404, 319},
        {270, 398, 331},
        {265, 392, 343},
        {259, 386, 355},
        {254, 380, 366},
        {250, 373, 377},
        {245, 367, 388},
        {241, 360, 399},
        {238, 353, 409},
        {234, 347, 420},
        {230, 341, 429},
        {227, 334, 439},
        {225, 327, 448},
        {222, 321, 458},
        {219, 315, 466},
        {217, 308, 475},
        {215, 302, 483},
        {213, 295, 492},
        {210, 290, 500},
        {209, 284, 508},
        {201, 255, 543},
        {195, 230, 575},
        {192, 205, 603},
        {189, 183, 628},
        {187, 163, 650},
        {185, 145, 670},
        {184, 129, 687},
        {183, 114, 703},
        {183, 100, 716},
        {183, 88, 729},
		    {183, 77, 740}
    };

    uint16_t scenario[5][3] = {
        {999, 0, 0},
        {837, 160, 4},
        {0, 999, 0},
        {183, 77, 740},
        {324, 436, 240}  
    };

//volatile uint16_t adc2_ordinary_valuetab[DMA1_CHANNEL1_BUFFER_SIZE];
/* add user code end private macro */

/* private variables ---------------------------------------------------------*/
/* add user code begin private variables */
float voltage ;
char uart_buffer[10];  // 字符数组用于存储转换后的字
double avg[3];  // 用于存储偶数和奇数位置的平均值
uint16_t Taith_out_R  = 999;
uint16_t Taith_out_G  = 999;
uint16_t Taith_out_B  = 999;
uint8_t CCT_mode_on = 1;

/* add user code end private variables */

/* private function prototypes --------------------------------------------*/
/* add user code begin function prototypes */
int fputc(int ch, FILE *p)
{
  usart_data_transmit(USART1, (uint8_t)ch);
  while (usart_flag_get(USART1, USART_TDC_FLAG) == RESET)
    ;
  ch = usart_data_receive(USART1);
  return ch;
}

void usart_send(usart_type *usart_x, uint8_t *data, uint16_t len)
{
  while (len)
  {
    while (usart_flag_get(USART1, USART_TDBE_FLAG) == RESET)
      ;
    usart_x->dt = (*data & 0x01FF);
    len--;
    data++;
  }
}

void usart1_dma_send(uint8_t *data, uint16_t len)
{
  
  dma_channel_enable(DMA1_CHANNEL2, FALSE);
  wk_dma_channel_config(DMA1_CHANNEL2,
                        (uint32_t)&USART1->dt,
                        (uint32_t)data,
                        len); // 修改为实际字符串长度
  dma_channel_enable(DMA1_CHANNEL2, TRUE);
  //while (usart_flag_get(USART1, USART_TDC_FLAG) == SET)
  //  ; // 等待发送完成
  while (usart1_tx_dma_status == 0)
    ; // 等待DMA传输完成
  usart1_tx_dma_status = 0;
}

void cyfartaledd(double *avg) {
    int sum0 = 0, sum1 = 0, sum2 = 0;
    int count0 = 0, count1 = 0, count2 = 0;

    // 遍历数组
    for (int i = 0; i < SIZE; i++) {
        if (i % 3 == 0) {  // 对应 0,3,6,9...
            sum0 += adc1_ordinary_valuetab[i];
            count0++;
        } else if ((i - 1) % 3 == 0) {  // 对应 1,4,7,10...
            sum1 += adc1_ordinary_valuetab[i];
            count1++;
        } else if ((i - 2) % 3 == 0) {  // 对应 2,5,8,11...
            sum2 += adc1_ordinary_valuetab[i];
            count2++;
        }
    }

    // 计算平均值
    avg[0] = (double)sum0 / count0;  // 第 0,3,6,9... 的平均值
    avg[1] = (double)sum1 / count1;  // 第 1,4,7,10... 的平均值
    avg[2] = (double)sum2 / count2;  // 第 2,5,8,11... 的平均值
}

int convert1(int num) {
    // 使用线性映射的方式进行转换
    // 公式为：y = (x - x_min) * (y_max - y_min) / (x_max - x_min) + y_min
    // 这里 x 是输入的数，x_min 是 0，x_max 是 1050，y_min 是 0，y_max 是 60
    //return (num * 60) / 999; 
    if (abs(num - lastNum) > 50) { // 判断变化是否超过50
      lastNum = num; // 更新上一次的输入值
      scenario_num = (num - 40) * 60 / (999 - 40);
      return scenario_num; // 如果变化不超过50，返回原值
    }
    else
    {
      return scenario_num; // 如果变化不超过50，返回原值
    }
}

uint8_t convert(int num) {
  //printf("num: %d\n", num);
  if (abs(num - lastNum) > 50) { // 判断变化是否超过50
    lastNum = num; // 更新上一次的输入值
    if ( num < 200)
    {
      scenario_num = 0;
      return 0;
    }
    else if (num >= 200 && num < 400)
    {
      scenario_num = 1;
      return 1;
    }
    else if (num >= 400 && num < 600)
    {
      scenario_num = 2;
      return 2;
    }
    else if (num >= 600 && num < 800)
    {
      scenario_num = 3;
      return 3;
    }
    else if (num >= 900 && num < 1000)
    {
      scenario_num = 4;
      return 4;
    }
    else 
    {
      return scenario_num; // 如果变化不超过50，返回原值
    }
  }
  else 
    {
      return scenario_num; // 如果变化不超过50，返回原值
    }
}



  uint8_t Newid_DIP_Mode () {

      float Foltedd_Port = avg[1] / 4095.0 * 3.3;

      if (CCT_mode_on == 0)
      {
        return 1;
      }
      if ( Foltedd_Port > 0.25 && Foltedd_Port < 0.35)  
      {
        return 1;
      }
      else if (Foltedd_Port > 0.6 && Foltedd_Port < 0.7)
      {
        return 2;
      }
      else if (Foltedd_Port > 1.0 && Foltedd_Port < 1.2)
      {
        return 3;
      }
      else if (Foltedd_Port > 1.35 && Foltedd_Port < 1.45)
      {
        return 4;
      }
      else if (Foltedd_Port > 1.60 && Foltedd_Port < 1.68)
      {
        return 5;
      }
      else
      {
        return 0;
      }
      
  }

  void CCT_mode()
  {
    uint8_t Cymhareb_pŵer = 0;
    uint8_t mode_id = Newid_DIP_Mode();
    switch (mode_id)
    {
    case 2:
      Cymhareb_pŵer = 0;
      Taith_out_R = rgb[Cymhareb_pŵer][0];
      Taith_out_G = rgb[Cymhareb_pŵer][1];
      Taith_out_B = rgb[Cymhareb_pŵer][2];
      break;
    case 3:
      Cymhareb_pŵer = 12;
      Taith_out_R = rgb[Cymhareb_pŵer][0];
      Taith_out_G = rgb[Cymhareb_pŵer][1];
      Taith_out_B = rgb[Cymhareb_pŵer][2];
      break;
    case 4:
      Cymhareb_pŵer = 37;
      Taith_out_R = rgb[Cymhareb_pŵer][0];
      Taith_out_G = rgb[Cymhareb_pŵer][1];
      Taith_out_B = rgb[Cymhareb_pŵer][2];
      break;
    case 5:
    Cymhareb_pŵer = 60;
      Taith_out_R = rgb[Cymhareb_pŵer][0];
      Taith_out_G = rgb[Cymhareb_pŵer][1];
      Taith_out_B = rgb[Cymhareb_pŵer][2];
      break;
    default:
      break;
    }
  }

/* add user code end function prototypes */

/* private user code ---------------------------------------------------------*/
/* add user code begin 0 */

/* add user code end 0 */

/**
  * @brief main function.
  * @param  none
  * @retval none
  */
int main(void)
{
  /* add user code begin 1 */

  /* add user code end 1 */

  /* system clock config. */
  wk_system_clock_config();

  /* config periph clock. */
  wk_periph_clock_config();

  /* nvic config. */
  wk_nvic_config();

  /* timebase config. */
  wk_timebase_init();

  /* init dma1 channel1 */
  wk_dma1_channel1_init();
  /* config dma channel transfer parameter */
  /* user need to modify define values DMAx_CHANNELy_XXX_BASE_ADDR and DMAx_CHANNELy_BUFFER_SIZE in at32xxx_wk_config.h */
  wk_dma_channel_config(DMA1_CHANNEL1, 
                        (uint32_t)&ADC1->odt, 
                        DMA1_CHANNEL1_MEMORY_BASE_ADDR, 
                        DMA1_CHANNEL1_BUFFER_SIZE);
  dma_channel_enable(DMA1_CHANNEL1, TRUE);

  /* init dma1 channel2 */
  wk_dma1_channel2_init();
  /* config dma channel transfer parameter */
  /* user need to modify define values DMAx_CHANNELy_XXX_BASE_ADDR and DMAx_CHANNELy_BUFFER_SIZE in at32xxx_wk_config.h */
  wk_dma_channel_config(DMA1_CHANNEL2, 
                        (uint32_t)&USART1->dt, 
                        DMA1_CHANNEL2_MEMORY_BASE_ADDR, 
                        DMA1_CHANNEL2_BUFFER_SIZE);
  dma_channel_enable(DMA1_CHANNEL2, TRUE);

  /* init dma1 channel3 */
  wk_dma1_channel3_init();
  /* config dma channel transfer parameter */
  /* user need to modify define values DMAx_CHANNELy_XXX_BASE_ADDR and DMAx_CHANNELy_BUFFER_SIZE in at32xxx_wk_config.h */
  wk_dma_channel_config(DMA1_CHANNEL3, 
                        (uint32_t)&USART1->dt, 
                        DMA1_CHANNEL3_MEMORY_BASE_ADDR, 
                        DMA1_CHANNEL3_BUFFER_SIZE);
  dma_channel_enable(DMA1_CHANNEL3, TRUE);

  /* init usart1 function. */
  wk_usart1_init();

  /* init wdt function. */
  wk_wdt_init();

  /* init adc1 function. */
  wk_adc1_init();

  /* init tmr3 function. */
  wk_tmr3_init();

  /* init tmr15 function. */
  wk_tmr15_init();

  /* init tmr16 function. */
  wk_tmr16_init();

  /* init tmr17 function. */
  wk_tmr17_init();

  /* add user code begin 2 */
  wk_delay_ms(200); // 延时200ms
  /* enable transfer full data interrupt */
  dma_interrupt_enable(DMA1_CHANNEL2, DMA_FDT_INT, TRUE); // 使能DMA传输完成中断

  /* dma1 channel2 interrupt nvic init */
  nvic_irq_enable(DMA1_Channel3_2_IRQn, 0, 0);

  /* enable transfer full data interrupt */
  dma_interrupt_enable(DMA1_CHANNEL3, DMA_FDT_INT, TRUE);

  /* dma1 channel3 interrupt nvic init */
  nvic_irq_enable(DMA1_Channel3_2_IRQn, 0, 0);
  usart_interrupt_enable(USART1, USART_IDLE_INT, TRUE);
  nvic_irq_enable(USART1_IRQn, 0, 0);

  usart_enable(USART1, TRUE);
  adc_ordinary_software_trigger_enable(ADC1, TRUE); // 启用 ADC1 的软件触发

  tmr_output_enable(TMR3, TRUE); // 使能 TMR13 的输出
  tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_1, 990); // 设置 TMR13 的通道 1 的比较值
  tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_2, 999); // 设置 TMR13 的通道 2 的比较值
  tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_4, 999); // 设置 TMR13 的通道 4 的比较值
  tmr_counter_enable(TMR3, TRUE); // 启动 TMR3 的计数器

  tmr_interrupt_enable(TMR17, TMR_OVF_INT, TRUE);
  tmr_interrupt_enable(TMR16, TMR_OVF_INT, TRUE);
  tmr_interrupt_enable(TMR15, TMR_OVF_INT, TRUE);

  /* reload wdt counter */
  //wdt_counter_reload();
  
  /* enable wdt */
  //wdt_enable();

  //printf("Hello World!\r\n");
  /* add user code end 2 */

  while(1)
  {
    /* add user code begin 3 */
    //wdt_counter_reload();

    if (usart1_rx_dma_status == 1)
    {
      usart1_rx_dma_status = 0;
      usart1_dma_send((uint8_t *)usart1_rx_buffer, usart1_rx_buffer_size);
    }
    if (Darllen_amserol_ADC_flag == 1)
    {
      Darllen_amserol_ADC_flag = 0;
      // 调用函数并传递指针
      cyfartaledd(avg);
      // 输出结果
      printf("偶数位置的平均值: %.2f\n", avg[0] / 4095.0 * 3.3 / 0.0025);
      printf("奇数位置的平均值: %.2f\n", avg[1] / 4095.0 * 3.3 );
      printf("接地点平均值: %.2f\n", avg[3] / 4095.0 * 3.3);
    }
    if (DIM_flag == 1 && Newid_DIP_Mode() == 1)
    {
      DIM_flag = 0;
      int cerrynt = avg[0] / 4095.0 * 3.3 / 0.0025;
      if (cerrynt > 999)
      {
        cerrynt = 999;
      }
      if (cerrynt < 45)
      {
        cerrynt = 40;
      }
      uint8_t Cymhareb_pŵer = convert( cerrynt );
      printf("Cymhareb_pŵer: %d\n", Cymhareb_pŵer);

      Taith_out_R = scenario[Cymhareb_pŵer][0];
      Taith_out_G = scenario[Cymhareb_pŵer][1];
      Taith_out_B = scenario[Cymhareb_pŵer][2];
      //tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_4, rgb[Cymhareb_pŵer][0]); 
      //tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_1, rgb[Cymhareb_pŵer][1]);
      //tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_2, rgb[Cymhareb_pŵer][2]);
      printf("Cymhareb_pŵer: %d\n", Cymhareb_pŵer);
      wk_delay_ms(100);
      /* code */
    }
    if (DIM_flag == 1 && Newid_DIP_Mode() != 1)
    {
      DIM_flag = 0;
      CCT_mode();
      usart1_dma_send( "CCT_mode\n" ,  strlen("CCT_mode\n"));
      //tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_4, 0); 
      //tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_1, 0);
    }
    
    // for (int i = 0; i < 61; i++) {
    //   tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_4, rgb[i][0]); 
    //   tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_1, rgb[i][1]);
    //   tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_2, rgb[i][2]);
    //   wk_delay_ms(100);
    // }
    //wk_delay_ms(300);
    // for (uint16_t i = 0; i < 999; i++)
    // {
    //   //wdt_counter_reload();
    //   tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_1, i); // 设置 TMR13 的通道 1 的比较值
    //   tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_2, 999 - i); // 设置 TMR13 的通道 2 的比较值
    //   tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_4, i); // 设置 TMR13 的通道 4 的比较值
    //   wk_delay_ms(10);
    //   voltage = ((float)adc1_ordinary_valuetab[0] / 4095.0) * 3.3 / 0.0025;
    //   sprintf(uart_buffer, "ADC_val: %.2fmA\n", voltage); // 将整数转换为字符串
    //   usart1_dma_send((uint8_t *)uart_buffer, strlen(uart_buffer));
    //   voltage = ((float)adc1_ordinary_valuetab[1] / 4095.0) * 3.3;
    //   sprintf(uart_buffer, "ADC_val2: %.2fV\n", voltage); // 将整数转换为字符串
    //   usart1_dma_send((uint8_t *)uart_buffer, strlen(uart_buffer));
    // }
    
    
    /* add user code end 3 */
  }
}

  /* add user code begin 4 */

  /* add user code end 4 */
